package com.example.controller;

import com.example.entity.AirspaceApproval;
import com.example.entity.UrlEntity;
import com.example.mapper.AirspaceApprovalMapper;
import com.example.service.AirspaceApprovalService;
import com.example.util.MicroResponseUtils;
import com.example.util.OSSUtil;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Controller
public class AirspaceApprovalController {
    @Autowired
    private AirspaceApprovalMapper airspaceApprovalMapper;
    @Autowired
    private AirspaceApprovalService airspaceApprovalService;
    @Autowired
    private OSSUtil ossUtil;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");


    @Deprecated
    @PostMapping("module3/searchsorted")
    public ResponseEntity pageSorted(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false, defaultValue = "application_acceptance_time") String sortedField,
            @RequestParam(required = false, defaultValue = "true") Boolean sortedOrder
            ) {
        List<AirspaceApproval> searchsorted = airspaceApprovalService.searchsorted(keyword, sortedField, sortedOrder);
        return ResponseEntity.ok(MicroResponseUtils.success(searchsorted));
    }

    @PostMapping("/module3/upload")
    public ResponseEntity uploadFile(@RequestParam("file") MultipartFile file) {
        UrlEntity urlEntity = new UrlEntity();
        if (file.isEmpty()) {
            urlEntity.setDocuments_receiving("ERROR");
            return ResponseEntity.ok(MicroResponseUtils.success(urlEntity));
        }

        try {
            // 保存文件到临时位置
            Path tempFilePath = Files.createTempFile(null, null);
            Files.write(tempFilePath, file.getBytes());

            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf('.') + 1);
            System.out.println(fileExtension);
            String dateStr = sdf.format(new Date());
            String pdfFilename = dateStr + "." + fileExtension;

            // 调用上传方法
            String fileUrl = ossUtil.upload(pdfFilename, tempFilePath.toFile().getAbsolutePath());

//            // 清理临时文件
//            Files.delete(tempFilePath);

            if (fileUrl.isEmpty()) {
                urlEntity.setDocuments_receiving("ERROR");
                return ResponseEntity.ok(MicroResponseUtils.success(urlEntity));
            }
            // 提取PDF首页并转换为图片
            PDDocument document = PDDocument.load(tempFilePath.toFile());
            PDFRenderer pdfRenderer = new PDFRenderer(document);

            // 渲染第一页为BufferedImage
            BufferedImage image = pdfRenderer.renderImageWithDPI(0, 300); // 提取第一页，DPI 300
            if(image==null){
                document.close();
                urlEntity.setDocuments_preview("ERROR");
                return ResponseEntity.ok(MicroResponseUtils.success(urlEntity));
            }
            String imageFileName =dateStr + ".png";
            // 保存图片到临时位置
            Path tempImageFilepath = Files.createTempFile(null, null);
            File tempImageFile = tempImageFilepath.toFile();
            boolean isImageWritten = ImageIO.write(image, "png", tempImageFile);
            // 检查图片是否成功写入
            if (!isImageWritten) {
                document.close();
                Files.delete(tempFilePath);
                urlEntity.setDocuments_preview("ERROR");
                return ResponseEntity.ok(MicroResponseUtils.success(urlEntity));
            }
            String imgurl = ossUtil.upload(imageFileName, tempImageFile.getAbsolutePath());
            urlEntity.setDocuments_receiving(fileUrl);
            urlEntity.setDocuments_preview(imgurl);
            return ResponseEntity.ok(MicroResponseUtils.success(urlEntity));
        } catch (IOException e) {
            urlEntity.setDocuments_receiving("ERROR");
            return ResponseEntity.ok(MicroResponseUtils.success(urlEntity));
        }
    }

    @PostMapping("/module3/save")
    public ResponseEntity updateUser(@RequestParam Integer id, @RequestBody AirspaceApproval airspaceApproval) {
        Optional<AirspaceApproval> update = airspaceApprovalService.update2(id, airspaceApproval);

        if (update.isPresent() || !Objects.equals(airspaceApproval.getDocumentsReceiving(), "ERROR")) {
            return ResponseEntity.ok(MicroResponseUtils.success(update.get()));
        } else {
            return ResponseEntity.ok(MicroResponseUtils.error("User not found"));
        }
    }

    @PostMapping("module3/searchandsort")
    public ResponseEntity searchAndSort(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false, defaultValue = "application_acceptance_time") String sortedField,
            @RequestParam(required = false, defaultValue = "true") Boolean sortedOrder
    ) {
        return ResponseEntity.ok(MicroResponseUtils.success(airspaceApprovalService.searchandsort(keyword, sortedField, sortedOrder)));
    }

}
